<template>
  <vab-card shadow="always">
    <template #header>
      <div class="flex_sb">
        <div class="flex leve2_title">
          采购产品信息
          <span class="pour_text flex">
            注：
            <sapn class="required_text">*</sapn>
            为必填项
          </span>
        </div>
      </div>
    </template>
    <div :class="{ warn_color: isWarn }">
      <el-form
        :ref="(el) => (productFormRef = el)"
        :model="productList"
        class="formData"
      >
        <el-table
          border
          height="300px"
          :data="productList"
          row-key="serial_number"
          v-loading="tableLoading"
          default-expand-all
        >
          <el-table-column label="序号" align="center" width="100">
            <template #default="{ row, $index }">
              <span>
                {{ row.serial_number }}
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" width="160">
            <template #header>
              <span class="required_text">*</span>
              <span>产品类型</span>
            </template>
            <template #default="{ row }">
              <sapn>{{ row.goods_type || '--' }}</sapn>
            </template>
          </el-table-column>
          <el-table-column align="center" width="200">
            <template #header>
              <span class="required_text">*</span>
              <span>产品条码</span>
              <vab-icon
                icon="search-line"
                style="color: #0967f4; margin-left: 12px"
                @click="handleLookAll"
              />
            </template>
            <template #default="{ row, $index }">
              <el-form-item prop="barcode">
                <LazySelect
                  type="barcode"
                  class="width_100"
                  :clearable="false"
                  v-model:value="row.barcode"
                  :customerNumber="customerNumber"
                  :disabled="row.goods_type == '赠品'"
                  @LazyChange="
                    (value: any) =>
                      productQuerySearch(row, value, 'barcode', $index)
                  "
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column min-width="200" align="center">
            <template #header>
              <span class="required_text">*</span>
              <span>产品名称</span>
              <vab-icon
                icon="search-line"
                style="color: #0967f4; margin-left: 12px"
                @click="handleLookAll"
              />
            </template>
            <template #default="{ row, $index }">
              <el-form-item prop="name">
                <LazySelect
                  type="name"
                  class="width_100"
                  v-model="row.name"
                  :clearable="false"
                  :customerNumber="customerNumber"
                  :disabled="row.goods_type == '赠品'"
                  @LazyChange="
                    productQuerySearch(row, row.name, 'name', $index)
                  "
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" width="160">
            <template #header>
              <span class="required_text">*</span>
              <span>品牌</span>
            </template>
            <template #default="{ row }">
              <sapn>{{ row.assistant_name || '--' }}</sapn>
            </template>
          </el-table-column>
          <el-table-column align="center" width="160">
            <template #header>
              <span class="required_text">*</span>
              <span>规格</span>
            </template>
            <template #default="{ row }">
              <sapn>{{ row.specification || '--' }}</sapn>
            </template>
          </el-table-column>
          <el-table-column align="center" width="200">
            <template #header>
              <span class="required_text">*</span>
              <span>采购数量</span>
            </template>
            <template #default="{ row, $index }">
              <el-form-item prop="buy_number">
                <VabNumberForm
                  :disabled="row.goods_type == '赠品'"
                  v-model.trim="row.buy_number"
                  :precision="0"
                  @input="
                    (value: any) => {
                      _getOrderDiscountMatch(value, row, $index, 'number')
                    }
                  "
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="remark" align="center" width="240">
            <template #header>
              <span>备注</span>
            </template>
            <template #default="{ row }">
              <el-form-item prop="remark">
                <VabInputForm
                  type="textarea"
                  v-model.trim="row.remark"
                  :disabled="row.goods_type == '赠品'"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="70">
            <template #default="{ row, $index }">
              <vab-icon
                v-if="row.goods_type != '赠品'"
                icon="add-circle-line"
                class="icon_color"
                @click="handleAdd(row, $index)"
              />
              <vab-icon
                v-if="row.goods_type != '赠品' && productList.length > 1"
                icon="delete-bin-5-line"
                @click="handleRemove(row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <ProductsAll
      ref="productsAllRef"
      :customerNumber="customerNumber"
      @handleShareSave="handleShareSave"
    />
  </vab-card>
</template>

<script setup lang="ts">
  defineOptions({
    name: 'ProductsInformation',
  })
  /**
   * @props
   */
  const props = defineProps({
    isWarn: {
      type: Boolean,
      default: false,
    },
  })

  /**
   * @import
   */
  import { ref } from 'vue'
  import ProductsAll from './ProductAll.vue'
  import {
    FieldFormat,
    FilterRepeat,
    IsValueHave,
    ReturnReduce,
    StrSplit,
  } from '/@/utils/utils'
  import LazySelect from '/@/components/lazySelect/buyerIndex.vue'
  import { _Message } from '~/src/utils/message'
  import { getCustomerProductList } from '~/src/api/dms/home/homeCustomer'
  import { orderDiscountMatch } from '~/src/api/dms/home/order'
  import _ from 'lodash'
  /**
   * @var
   */
  const tableLoading = ref(false)
  const storage: any = localStorage.getItem('userInfo')
  const userInfo: any = JSON.parse(storage)
  const proxy: any = getCurrentInstance()?.proxy

  const productFormRef = ref()

  const customerNumber = ref('')
  const productsAllRef = ref<any>(null)
  // 基础五个数据
  const productList = ref<any>([
    {
      serial_number: 1,
      down_price: 0,
      base_price: 0,
      goods_type: '正品',
      children: [],
    },
  ])
  /**
   * @method
   */

  // 添加
  const handleAdd = async (row: any, i: number) => {
    productList.value.splice(i + 1, 0, {
      buy_number: '',
      goods_type: '正品',
      children: [],
    })

    orderSort()
  }
  // 删除
  const handleRemove = async (row: any) => {
    productList.value = await productList.value.filter(
      (item: any) => item.serial_number != row.serial_number
    )
    orderSort()
  }

  // 查看全部产品
  const handleLookAll = () => {
    if (!customerNumber.value) {
      proxy.$Message('请选择买方，再进行操作！', 'warning')
      return
    }
    productsAllRef.value.open()
  }

  // 排序
  const orderSort = () => {
    // 订单列表排序
    productList.value = productList.value.map((item: any, index: any) => {
      if (item.children) {
        return {
          ...item,
          serial_number: index + 1,
          children: item.children.map((item: any, i: any) => {
            return {
              ...item,
              serial_number: index + 1 + '.' + (i + 1),
            }
          }),
        }
      }
      return { ...item, serial_number: index + 1 }
    })
  }

  // 校验买方
  const clearProduct = async (value: string, lay = false) => {
    customerNumber.value = value

    if (lay) {
      productList.value = [
        {
          name: '',
          number: '',
        },
      ]
      productsAllRef.value.handleReset()
    }
  }

  // 产品价格带出基本信息
  const productQuerySearch = async (
    mode: any,
    value: string | number,
    type = '',
    index = 0
  ) => {
    if (type == 'assistant_id') return
    if (!customerNumber.value) return

    const res = await getCustomerProductList({
      page: 1,
      limit: 2000,
      customer_number: customerNumber.value,
      filter: {
        number: type == 'number' ? value : '',
        name: type == 'name' ? value : '',
        barcode: type == 'barcode' ? value : '',
      },
    })

    if (!res.data.list.length) {
      proxy.$Message('无该产品信息！', 'warning')
      return
    }

    const row = res.data.list[0]
    const { assistant_name, name, number, barcode, specification } = row

    if (productList.value.length > 1) {
      let voidNumber = false
      voidNumber = productList.value.some(
        (item: any) => item.number == row.number
      )

      if (voidNumber) {
        proxy.$Message('编码重复,请重新选择！', 'warning')
        productList.value.forEach((el: any, i: number) => {
          if (el.serial_number == mode.serial_number) {
            productList.value[i] = { goods_type: '正品' }
          }
        })
        orderSort()
        return
      }
    }

    productList.value.forEach((el: any, i: number) => {
      if (el.serial_number == mode.serial_number)
        productList.value[i] = {
          assistant_name,
          name,
          barcode,
          number,
          specification,
          goods_type: '正品',
          children: [],
        }
    })
    await orderSort()
  }
  // 查看全部 返回数据
  const handleShareSave = async (list: any) => {
    if (!list.length) return
    tableLoading.value = true

    // 筛选合适的
    const _productList = productList.value.filter((item: any) => {
      return item.number
    })
    // 合并
    const Array = await list.concat(_productList)
    // 去重
    const FilterArray = await FilterRepeat(Array, 'number')

    productList.value = FilterArray
    tableLoading.value = false

    await orderSort()
  }

  // 字段级格式化
  const _FieldFormat = (value: string, type = '') => {
    return FieldFormat(value, type, 2)
  }

  // 获取赠品信息
  const _getOrderDiscountMatch = async (
    value: string | number,
    row: any,
    i: number,
    type: string
  ) => {
    // 选中条是否有值
    if (!IsValueHave(row)) return
    const { number } = row

    // 对应值是否有值
    if (!IsValueHave(number) && !IsValueHave(value)) return
    // 产品类型不是赠品 || 采购数量为 0
    if (!IsValueHave(value) || value == 0) {
      row.children = []
      return
    }

    try {
      let res = await orderDiscountMatch({
        buyer_customer_uid: userInfo.uid, //客户id
        product_code: number || '', //产品编码
        number: value || '', //购买数量
      })

      // 获取 编码集合
      const { item_list } = res.data

      if (!item_list.length) {
        row.children = []
        return
      }

      row.children = item_list.map((item: any, k: number) => {
        return {
          ...item,
          goods_type: '赠品',
          buy_number: item.goods_num || 1,
          number: item.goods_no,
          barcode: item.goods_barcode,
          name: item.goods_name,
          specification: item.specification,
          assistant_name: item.brand_name,
        }
      })

      await orderSort()
    } catch (error) {}
  }

  // 获取复制数据
  const getUpdateData = async ({ detail }: any) => {
    productList.value = [
      {
        serial_number: 1,
        down_price: 0,
        base_price: 0,
        goods_type: '正品',
        children: [],
      },
    ]
    if (!IsValueHave(detail)) return

    tableLoading.value = true

    const list = _.cloneDeep(
      detail.map((item: any) => {
        return {
          ...item,
          father_key:
            item.goods_type == '赠品'
              ? StrSplit(item.serial_number, '.', 0)
              : '',
          son_key:
            item.goods_type == '赠品'
              ? StrSplit(item.serial_number, '.', 1)
              : '',
          buy_number: item.number,
          number: item.product_code,
          barcode: item.product_barcode,
          specification: item.specification,
          name: item.product_name,
          assistant_name: item.brand,
          children: [],
        }
      })
    )

    const fatherArray = list.filter((item: any) => {
      if (item.goods_type != '赠品') return item
    })
    const sonArray = list.filter((item: any) => {
      if (item.goods_type == '赠品') return item
    })

    await fatherArray.forEach((item: any, i: number) => {
      sonArray.forEach((jtem: any) => {
        if (item.serial_number == jtem.father_key) {
          item.children.push(jtem)
        }
      })
    })

    productList.value = fatherArray

    tableLoading.value = false
  }

  /**
   * @实例
   */
  //抛出数据
  defineExpose({
    productFormRef,
    productList,
    getUpdateData,
    clearProduct,
  })
</script>

<style lang="scss" scoped>
  :deep() {
    .el-loading-spinner {
      display: none;
    }
  }

  .formData {
    :deep() {
      .el-form-item {
        margin-bottom: 0px;
      }
    }

    .icon_color {
      color: #0967f4;
      margin-right: 4px;
    }
  }

  .giftBox {
    :deep() {
      thead .is-leaf {
        background-color: #fff8e1 !important;
      }
    }
  }
</style>
